import { defineStore } from 'pinia';
import { type UserState } from './types';
import { $fetch } from '@/settings/utils/fetch';
import { ref } from 'vue';

const useUserStore = defineStore('user', () => {
  const getInitUser = (): UserState => ({
    id: undefined,
    photo: undefined,
    username: undefined,
    nickname: undefined,
    email: undefined,
    roles: [],
  });

  const user = ref<UserState>(getInitUser());

  const setInfo = (partial: Partial<UserState>) => {
    user.value = { ...user.value, ...partial };
  }

  const resetInfo = () => {
    user.value = getInitUser();
  }

  // Get user's information
  const fetchInfo = async () => {
    if (import.meta.env.VITE_MOCK_LOGIN === 'yes') {
      setInfo({
        id: '1',
        photo: 'https://lf1-xgcdn-tos.pstatp.com/obj/vcloud/vadmin/start.8e0e4855ee346a46ccff8ff3e24db27b.png',
        email: 'wangliqun@email.com',
        username: 'wangliqun',
        nickname: 'wlq',
        roles: ['admin'],
      });

      return {
        isSuccess: true,
        code: 200,
      };
    }
    else {
      const { isSuccess, data, msg, code } = await $fetch('/admin/user/currentUserInfo');

      if (isSuccess) {
        setInfo({
          id: data.id,
          photo: data.photo,
          email: data.email,
          username: data.username,
          nickname: data.nickname,
          roles: data.roles ?? [],
        });
      }

      return { isSuccess, msg, code: Number(code) };
    }
  }

  return { user, setInfo, resetInfo, fetchInfo };
});

export default useUserStore;
